﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;

namespace _5E.Utils.DbHelper.EasySQL
{
    /// <summary>
    /// 程序说明：SQL创建者
    /// 创建作者：ahl5esoft
    /// 创建时间：2012-04-16
    /// </summary>
    internal class Parser
    {
        #region 变量

        private const string ELEMENT_PK_NAME = "pk";

        private const string ELEMENT_FK_NAME = "fk";

        private const string ELEMENT_OTHER_NAME = "column";

        private const string COLUMN_ELEMENT_NAME = "name";

        private const string PROPERTY_ELEMENT_NAME = "property";

        #endregion

        #region 静态方法

        public static EasyDbTable ParseMapping(string mappingPath)
        {
            var filePath = GetFilePath(mappingPath);
            var mapping = XElement.Load(filePath);
            var easyDbColumns = new List<EasyDbColumn>();
            foreach (var element in mapping.Elements())
            {
                var columnType = GetColumnType(element.Name.ToString());
                var easyDbColumn = new EasyDbColumn(element.Attribute(COLUMN_ELEMENT_NAME).Value, element.Attribute(PROPERTY_ELEMENT_NAME).Value, columnType);
                easyDbColumns.Add(easyDbColumn);
            }
            return new EasyDbTable(mapping.Name.LocalName, easyDbColumns.ToArray());
        }

        private static string GetFilePath(string mappingPath)
        {
            var filePath = DbFactory.MappingDirectory + mappingPath;
            var exist = File.Exists(filePath);
            if (exist)
            {
                return filePath;
            }
            else
            {
                throw new ArgumentNullException("实体映射路径不正确!");
            }
        }

        private static EasyDbColumnType GetColumnType(string elementName)
        {
            var columnType = EasyDbColumnType.Normal;
            if (elementName == ELEMENT_PK_NAME)
            {
                columnType = EasyDbColumnType.PK;
            }
            else if (elementName == ELEMENT_FK_NAME)
            {
                columnType = EasyDbColumnType.FK;
            }
            return columnType;
        }

        #endregion
    }
}
